package com.newtouch.avmarketing.mgr.modules.avmarkrting.api;

import com.newtouch.avmarketing.mgr.modules.avmarkrting.entity.dto.DoubleAuditingDto;
import com.newtouch.avmarketing.mgr.modules.avmarkrting.service.DoubleAuditingDtoService;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
@RequestMapping("/tpzhurl")
@Slf4j
public class VideoPlay {

    @Autowired
    private DoubleAuditingDtoService doubleAuditingDtoService;

    @RequestMapping(value = "/url/{policyCode}",method = RequestMethod.GET)
    @Transactional
    public void urlZh(HttpServletResponse response
            ,@ApiParam("policyCode") @PathVariable String policyCode) throws Exception{
        try {
            //https://edu-0310.oss-cn-shanghai.aliyuncs.com/2021/06/01-%E6%A6%82%E8%A6%81.mp4
            DoubleAuditingDto doubleAuditingDto = doubleAuditingDtoService.findDoubleAuditingDto(policyCode);
            if (doubleAuditingDto != null){
                String path = doubleAuditingDto.getVideoPath();
                System.out.println("path:"+path);

                byte data[] = readInputStream(path);
                response.setContentType("video/mp4"); //设置返回的文件类型
                OutputStream os = response.getOutputStream();
                os.write(data);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static byte[] readInputStream(String path) throws Exception{
        InputStream inStream = new FileInputStream(path);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}
